home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 12834 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.3 KB  |  50 lines

  1. Path: noc.netcom.net!news
  2. From: Tarang Deshpande <tarang@willows.com>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Rounding a double
  5. Date: Tue, 02 Apr 1996 17:00:40 -0800
  6. Organization: NETCOM Network Operations
  7. Message-ID: <3161CDB8.6BB5@willows.com>
  8. References: <4jprh2$1li@newsgate.dircon.co.uk>
  9. NNTP-Posting-Host: daffy.willows.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0GoldB2 (Win95; I)
  14.  
  15. Peter Smith wrote:
  16. > Has anybody got a C function to round a double to a number of decimal
  17. > places that:
  18. > a) is readable
  19. > b) is relatively short
  20. > c) works !!
  21. > I had a function but it failed if the number of decimal places was zero,
  22. > if the double was very small,  .. . etc etc.
  23. > Is there a library of freeware C functions anywhere on the Internet ??
  24. > Many thanks
  25. > Pete
  26. > replies to : pg-smith@dircon.co.uk
  27.  
  28. How about:
  29.  
  30. #include <math.h>
  31. double rounddouble ( double number, int decimals )
  32. {
  33.  
  34.     long roundednumber;
  35.  
  36.     /* shift the decimal to the right by decimals places add 0.5 and truncate */
  37.     roundednumber = ( long ) ( number * pow ( 10, decimals ) + 0.5 );
  38.  
  39.     /* shift the decimal to the left by decimals places */
  40.     number = ( double )roundnumber / pow ( 10, decimals );
  41.  
  42.     return ( number );
  43. }
  44.     
  45. Tarang
  46.